import React from 'react';
import { connect } from 'dva';
import {  Button, Modal, Form, Input,  DatePicker,Select, Table, Popconfirm, Divider } from 'antd';
import moment from 'moment';
import _ from 'lodash';
import dispatch from 'dva'
const Option = Select.Option;
@connect(({ version }) => ({
}))
export default class extends React.Component {

  cancel = () => {
    this.props.dispatch({
      type: 'version/setVisible',
      payload: false
    })
  };

  render() {
    const { visible } = this.props;
    return (
      <Modal
        visible={visible}
        destroyOnClose={true}
        title="项目版本管理"
        cancelText="关闭"
        onCancel={this.cancel}
        okButtonProps={{ style: { display: "none" }, disabled: true }}
        width={1000}
      >
        <VersionTable />
      </Modal>
    );
  }
}

// table row 定义：每一行就是一个form表单（使用了context：可全局传递值，父子组件无需通过props连续传值）
const FormRowContext = React.createContext();
const FormRow = Form.create()(
  class extends React.Component {
    render() {
      return (
        <FormRowContext.Provider value={this.props.form}>
          <tr {...this.props} />
        </FormRowContext.Provider>
      );
    }
  }
);

//table cell 定义：每个单元格，对应 Form 的 Item
@connect(({ version }) => ({
  versionList:version.versionList,
  editingKey:version.editingKey,
}))
class FormCell extends React.Component {
  getVersionOpion =(data)=>{
    if(data){
      let list = data.map(r=> <Option key={r.vname} >{r.vname}</Option>)
      return list
    }
    return <Option key='---' >----</Option>
  }

  getInput = (inputType,editingKey,record,versionList) => {
    if(inputType == 'date'){
      return <DatePicker size='small' format='YYYY-MM-DD' style ={{ width: 130 }}/>     
    }else if(inputType =='pick'){
      // 更新时 版本号不可修改
      return <Select disabled={!!(editingKey && editingKey === record.key)} value="small" style=  {{ width: 180 }}>
        {this.getVersionOpion(versionList)}
      </Select> 
    }
    return <Input />;
  };

  getInitialValue = (inputType, record, dataIndex) => {
    let value = record[dataIndex];
    if(record.key == 0 && inputType =='date'){
      return null;
    }
    if(inputType == 'date'){
      return moment(value, 'YYYY-MM-DD');
    }
   return value; 
  }

  render() {
    const {
      adding,
      editing,
      dataIndex,
      title,
      inputType,
      record,
      index,
      versionList,
      editingKey,
      ...restProps
    } = this.props;

    return (
      <FormRowContext.Consumer>
        {(form) => {
          const { getFieldDecorator } = form;
          return (
            <td {...restProps}>
              { adding || editing ? (
                <Form.Item style={{ margin: 0 }}>
                  {getFieldDecorator(dataIndex, {
                    rules: [{
                      required: true,
                      message: `请输入"${title}"!`,
                    }],
                    initialValue: this.getInitialValue(inputType, record, dataIndex),
                  })(this.getInput(inputType,editingKey,record,versionList))}
                </Form.Item>
              ) : restProps.children}
            </td>
          );
        }}
      </FormRowContext.Consumer>
    );
  }
  
}

// Version 表格
@connect(({ version,testreport, loading }) => ({
  list: version.list,
  projectId: version.projectId,
  editingKey: version.editingKey,
  versionList:version.versionList,
  loading: loading.models.testcenter_version
}))
class VersionTable extends React.Component {
  constructor(props) {
    super(props);
    this.columns = [
      { key: 'name', title: '版本号', dataIndex: 'name', editable: true,width:180,
      render: (record) => {
        return(<div style={{width:180}}>{record}</div>)}},
      { key: 'expectTestTime', title: '预计提测日期', dataIndex: 'expectTestTime', editable: true , width:160},
      { key: 'expectVersionReleaseTime', title: '预计发布日期', dataIndex: 'expectVersionReleaseTime', editable: true, width:160 },
      { key: 'selfTestCaseUrl', title: '自测用例地址', dataIndex: 'selfTestCaseUrl', editable: true, width: 300 ,
      render: (record) => {
        return(<div style={{width:300}}>{record}</div>)}
      },
      { 
        title: '操作',
        width:100,
        render: (text, record) => {
          const editable = this.isEditing(record);
          const editing = this.inEditing();
          const domDefaultAdd = (<div style={{textAlign:'center'}}>
            <FormRowContext.Consumer>
              {form => (
                <Button onClick={() => this.save('add', form, record.key)} disabled={ editing } >
                
                  <a href="javascript:;" style={{ marginRight: 8 }} > 添加 </a>
                </Button>
              )}
            </FormRowContext.Consumer>
          </div>)
          const domInEditing = (<span>
            <FormRowContext.Consumer>
              {form => (
                <a
                  href="javascript:;"
                  onClick={() => this.save( 'edit', form, record.key)}
                  style={{ marginRight: 8 }}
                >
                  保存
                </a>
              )}
            </FormRowContext.Consumer>
              <a onClick={() => this.cancel(record.key)}>取消</a>
          </span>)
          const domBeforeSave = ((
            <div>
              <a onClick={() => this.edit(record.key)}>更新</a>
              <Divider type="vertical" />
              <Popconfirm title="确定删除此版本吗?" onConfirm={() => this.delete(record.key,record)}>
                <a href="javascript:;">删除</a>
              </Popconfirm>
            </div>
          ))

          if(record.key == 0){
            return domDefaultAdd;
          }
          return (
            <div style={{width:100}}>
              { editable ? domInEditing : domBeforeSave }
            </div>
          );
        },
      }
    ];

  }

  edit(key) {
    this.props.dispatch({
      type:'version/setEditingKey',
      payload:key
    })
  }

  cancel = () => {
    this.props.dispatch({
      type:'version/setEditingKey',
      payload:''
    })
  };

  delete = (key,record) => {
    this.props.dispatch({
      type: 'version/delete',
      params: key
    });

    this.props.dispatch({
      type:'testreport/deleteReport',
      payload:{
                projectId:this.props.projectId,
                version: record.name,
                versionId:record.id
              }
    })
  }

  //表单提交，新建：status=1 编辑：status=2
  save(status, form, key) {
    form.validateFields((error, rowValues) => {
      if (error) {
        return;
      }
      //提交表单数据，请求后台服务
      let actionType = status=='add' ? 'version/add': status=='edit' ? 'version/edit':'';
      this.props.dispatch({
        type: actionType,
        params: {id: key, ...rowValues}
      });
      if(status =='add'){
        this.props.dispatch({
          type:'testreport/add',
          payload:{projectId: this.props.projectId,
                   version:rowValues.name}
        })
      }
      if(status == 'add'){
        form.resetFields();
      }
    });
  }

  inEditing = () => {
    return this.props.editingKey === '' ? false : true;
  }

  isEditing = (record) => {
    return record.key === this.props.editingKey;
  };

  isAdding = (record) => {
    return record.key === 0;
  }

  render() {
    const {versionList} = this.props;
    const components = {
      body: {
        row: FormRow,
        cell: FormCell,
      },
    };

    const columns = this.columns.map((col) => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          inputType: col.dataIndex == 'expectTestTime' ||  col.dataIndex == 'expectVersionReleaseTime' ? 'date' : col.dataIndex == 'name'? 'pick': 'text',
          dataIndex: col.dataIndex,
          title: col.title,
          editing: this.isEditing(record),
          adding: this.isAdding(record)
        }),
      };
    });
    //第一行默认为添加
    const defaultAddRowData = { key: 0, name:versionList.length>0? versionList[0].vname:'', expectVersionReleaseTime: '', expectTestTime: '', selfTestCaseUrl: '' }
    return (
      <div>
        <Table 
          columns={columns} 
          components={components}  
          dataSource={[defaultAddRowData, ...this.props.list]}
          loading={this.props.loading}  bordered  size="small"
        ></Table>
      </div>
    );
  }
}
